#include "tailwindcssdoc.h"

#include <qrcutil.h>

TailwindcssDoc::TailwindcssDoc() {
    foreach (auto block, QR("://tailwindcss.txt").split("\n\n", Qt::SkipEmptyParts)) {

        QString h5 = "";
        foreach (auto line, block.split("\n", Qt::SkipEmptyParts)) {

            if (line.startsWith("<h5>")) {
                h5 = line.mid(line.indexOf(">")+1);
                h5 = h5.mid(0, h5.indexOf("<"));
                continue;
            }

            auto title = line.mid(line.indexOf(">")+1);
            title = title.mid(0, title.indexOf("<"));
            auto href = line.mid(line.indexOf("href=\"")+6);
            href = href.mid(0, href.indexOf("\">"));

            KV kv(title, href);
            if (m_category_pairs.contains(h5) == false) {
                m_category_pairs.insert(h5, QList<KV>());
            }
            auto list = m_category_pairs.value(h5);
            list << kv;
            m_category_pairs.insert(h5, list);
        }
        m_categories << h5;
    }
}

QString TailwindcssDoc::name()
{
    return "TailwindcssDoc";
}

QString TailwindcssDoc::prefix()
{
    return "https://tailwindcss.com";
}

QStringList TailwindcssDoc::searching(const QString &text)
{
    QStringList list;
    if (m_interactive == 0) {
        foreach (auto var, m_categories) {
            if (text.isEmpty() || var.contains(text, Qt::CaseInsensitive)) {
                list << var;
            }
        }
    }
    if (m_interactive == 1) {
        auto kvs = m_category_pairs.value(m_category);
        foreach (auto var, kvs) {
            if (text == m_category || text.isEmpty() || var.first.contains(text, Qt::CaseInsensitive)) {
                list << var.first;
            }
        }
    }
    return list;
}

QString TailwindcssDoc::content(const QString &text)
{
    auto kvs = m_category_pairs.value(m_category);
    foreach (auto var, kvs) {
        if (var.first.contains(text)) {
            if (var.second.startsWith("http")) {
                return var.second;
            }
            return prefix() + var.second;
        }
    }
    return "";
}

bool TailwindcssDoc::interactive(const QString &text)
{
    if (m_interactive == 0) {
        m_category = text;
        return m_interactive++ < 1;
    }
    return false;
}

bool TailwindcssDoc::interactive_running()
{
    return m_interactive == 0;
}

void TailwindcssDoc::interactive_restore()
{
    m_interactive = 0;
}
